import { createStore } from 'vuex'
const setLocalStorage = state => {
  const { cartList } = state
  const cartListString = JSON.stringify(cartList)
  localStorage.cartList = cartListString
}
const getLocalStorage = () => {
  if (localStorage.cartList) {
    return JSON.parse(localStorage.cartList)
  }
  return {}
}
export default createStore({
  state: {
    //     cartList: {
    //       // 第一层级是shopid   商铺的id
    //      shopid:{
    // /    shopName：“沃尔玛”
    //      productList：{
    //        productid: {}
    // }
    //       }
    //     }
    cartList: getLocalStorage()
  },
  mutations: {
    ChangeCartItemInfo(state, payload) {
      const { shopId, productId, productInfo, num } = payload
      const shopInfo = state.cartList?.[shopId] || {
        shopName: '',
        productList: {}
      }
      let product = shopInfo.productList[productId]
      if (!product) {
        product = productInfo
        product.count = 0
      }
      product.count += num
      if (product.count < 0) {
        product.count = 0
      }
      if (product.count > 0) {
        product.check = true
      }
      shopInfo.productList[productId] = product
      state.cartList[shopId] = shopInfo
      // console.log(state.cartList)
      setLocalStorage(state)
    },
    changeCartItemChecked(state, payload) {
      const { shopId, productId } = payload
      const prodct = state.cartList[shopId].productList[productId]
      prodct.check = !prodct.check
      setLocalStorage(state)
    },
    clearCartProducts(state, payload) {
      const { shopId } = payload
      state.cartList[shopId].productList = {}
      setLocalStorage(state)
    },
    setCartItemChecked(state, payload) {
      const { shopId } = payload
      const productList = state.cartList[shopId].productList
      for (const key in productList) {
        productList[key].check = true
      }
      setLocalStorage(state)
    },
    changeShopName(state, payload) {
      const { shopId, shopName } = payload
      const shopInfo = state.cartList[shopId] || {
        shopName: '',
        productList: {}
      }
      shopInfo.shopName = shopName
      state.cartList.shopId = shopInfo
      setLocalStorage(state)
    },
    clearCartData(state, payload) {
      const { shopId } = payload
      state.cartList[shopId].productList = {}
    }
  },
  actions: {},
  modules: {}
})
